package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.Constants;
import com.qf.utils.MD5Utils;
import com.qf.utils.RandomUtils;

public class UserServiceImpl implements UserService {
    @Override
    public User login(String userName, String password) {
        UserDao userDao=new UserDaoImpl();
        User user=userDao.findByUserName(userName);

        if(user==null){
            return null;
        }
        if(!Constants.USER_ACTIVE.equals(user.getStatus())){
            return null;
        }
        if(Constants.ROLE_ADMIN==user.getRole()){
            return null;
        }
        String md5Pwd = MD5Utils.md5(password);
        if(md5Pwd.equals(user.getPassword())){
            return user;
        }
        return null;
    }

    @Override
    public boolean check(String userName) {
        UserDao userDao=new UserDaoImpl();
        User user=userDao.findByUserName(userName);
        if(user==null){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int createUser(User user) {
        String md5= MD5Utils.md5(user.getPassword());
        user.setPassword(md5);
        user.setStatus(Constants.USER_ACTIVE);
        user.setRole(Constants.ROLE_CUSTOMER);
        user.setCode(RandomUtils.createActive());
        UserDao userDao=new UserDaoImpl();
        int count = userDao.addUser(user);

        return count;
    }
}
